/*TagCursorAdapter.java
 * Displays tags
 * 
 */
package com.tagit;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import com.tagit.MyApp;


public class TagCursorAdapter extends BaseAdapter {

	private Cursor mCursor;
	private Context mCtx;
	private PhotosDbAdapter db;
	private PhotoCursorAdapter mCursorAdapter;
	
	public TagCursorAdapter(Cursor c, Context ctx) {
		mCursor = c;
		mCtx = ctx;
		db = new PhotosDbAdapter(ctx);
		db.open();
		mCursorAdapter = MyApp.getAdapter();
	}
	//@Override
	public int getCount() {
		return mCursor.getCount();
	}

	//@Override
	public Object getItem(int position) {
		if (position >= getCount()) {
			return null;
		}
		
		mCursor.moveToPosition(position);
		int colIdx = mCursor.getColumnIndex(PhotosDbAdapter.KEY_TAG_CONTENT);
		return mCursor.getString(colIdx) + " x";
	}

	//@Override
	public long getItemId(int position) {
		if (position >= getCount()) {
			return -1;
		}
		
		mCursor.moveToPosition(position);
		return mCursor.getLong(mCursor.getColumnIndex(PhotosDbAdapter.KEY_ID));
	}

	//@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Button b;
		
		
		if (convertView == null) {
			b = new Button(mCtx);
			b.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.MATCH_PARENT,
					GridView.LayoutParams.MATCH_PARENT));
			
	
		}
		else {
			b = (Button) convertView;
		}
		b.setText((String) getItem(position));
		
		b.setOnClickListener(new DeleteListener(position));
		
		return b;
	}
	
	private class DeleteListener implements View.OnClickListener {

		int mPos;
		
		private DeleteListener(int pos) {
			mPos = pos;
		}
		
		//@Override
		public void onClick(View v) {
			long id = getItemId(mPos);
			
			//db.removeTag(id);
			db.removeTagMsg(id, v, mCursorAdapter);
			
			//OMG HAX!! This is really broken but should work.
			//ViewPhoto hax = (ViewPhoto) mCtx;
			//hax.fill_tag_table();
		}
		
	}

}
